<template>
	<view>
		<view class="private-chat-main">
			<view class="private-chat-head">
				<view class="content-swiper-head-left">
					<uni-icons type="back" color="#333" size="30" @click="goBack()"></uni-icons>
					<view class="private-chat-name-left">
						<view class="private-chat-name">
							<text>{{ state.userInfo.ShowName }}</text>
							<Ident :userInfo="state.userInfo" />
						</view>
						<text class="on-line" v-if="onIsLineFn(state.userInfo.LastOnline * 1000)">{{
							onLineFn(state.userInfo.LastOnline * 1000)
						}}</text>
						<text class="out-line" v-else>离线</text>
					</view>
				</view>
				<view class="content-swiper-head-right" v-if="state.isAuth">
					<Attention v-if="!state.userInfo.IsFollow && state.userIMId != 215" :followUserID="state.userInfo.ID"
						@update:isFollowUpdate="ev => state.userInfo.IsFollow = ev" />
					<uni-icons type="more-filled" color="#333" size="30" @click="squareFn()"></uni-icons>
				</view>
			</view>
			<view class="private-chat-main-box">
				<scroll-view :scroll-top="state.scrollTop" scroll-y="true" class="scroll-Y">
					<view class="private-chat-main-list" ref="scrollRef">
						<view class="chat-tips-box">
							<view class="chat-tips">请规范你的言行，如发现色情、诈骗、政治等违法行为封号处理！</view>
						</view>
						<template v-for="item in state.chatList" :key="item.idClient">
							<ChatList :itemData="item" :leftUser="state.userInfo"></ChatList>
						</template>
					</view>
				</scroll-view>
			</view>
			<view class="private-chat-input">
				<view class="private-chat-input-top">
					<van-field v-model="state.msg" placeholder="输入消息..." /><img @click="state.giftShow = !state.giftShow"
						src="@/assets/image/icon81.png" alt="">
					<van-button type="primary" size="small" @click="sendFn()">发送</van-button>
				</view>
				<view class="private-chat-input-bottom">
					<view class="private-chat-input-item" v-if="state.userIMId != 215">
						<ReviewGift :userImId="state.userIMId" @successActionGift="successActionGift">
							<template v-slot:gift-box>
								<img src="@/assets/image/icon82.png" alt="" class="img-item">
							</template>
						</ReviewGift>
					</view>
					<view class="private-chat-input-item">
						<view class="content-swiper-bottom-message-gift" @tap="successImg">
							<img src="@/assets/image/icon83.png" class="img-item">
						</view>
					</view>
				</view>
				<view class="gift-list-main" v-if="state.giftShow">
					<GiftList @update:itemCurGift="ev => state.itemCurGift = ev" />
					<PaySend :itemCurGift="state.itemCurGift" />
				</view>
			</view>
		</view>
		<AuthPup :types="state.types" v-if="state.isAuthPup" ref="AuthPupRef">
			<template #auth>
				<OpenMember :curIndex="state.memberType" :IsVipImCount="state.IsVipImCount" :userInfo="state.userInfo"
					@TrendUnLockSuccess="TrendUnLockSuccess" :tipsName="state.tipsName" />
			</template>
		</AuthPup>
		<ActionSheetBox :actionsArr="state.actions" :currentItem="state.userInfo"
			:imId="state.userInfo && state.userInfo.IMId" ref="ActionSheetRef" />
	</view>
</template>

<script setup>
import {
	reactive,
	ref,
	getCurrentInstance,
	onMounted,
	computed,
	nextTick
} from "vue"
import {
	getAuthorization,
	setAuthorization
} from "@/utils/auth.js"
import Ident from "@/pages/home/components/ident/index.vue"
import ChatList from "@/components/chatList/index.vue"
import ReviewGift from "@/pages/home/components/reviewGift/index.vue"
import SendImg from "@/components/sendImg/index.vue"
import GiftList from "@/pages/home/components/giftList/index.vue"
import PaySend from '@/pages/home/components/paySend/index.vue'

import {
	onLoad
} from '@dcloudio/uni-app'

import {
	UserInfo
} from "@/api/person/index.js"

const lower = () => {
	state.scrollTop = 0
}

let {
	proxy
} = getCurrentInstance()

const state = reactive({
	show: false,
	curIndex: false,
	actions: [{
		name: '清空聊天记录'
	},
	{
		name: '举报'
	},
	{
		name: '拉黑'
	},
	],
	msg: "",
	giftShow: false,
	isAuth: false,
	itemCurGift: {},
	userInfo: {},
	curItem: {},
	userIMId: "",
	chatList: [],
	scrollTop: 1000,
	types: 1,
	isAuthPup: false,
	memberType: "1", // 类型 1 女性用户 2 为男性用户
	curUserInfo: {}, // 自己
	IsVipImCount: 0, // 男性vip用户剩余解锁次数
	tipsName: '开通会员', // 男性用户 
})

import {
	AuthStateStore
} from "@/store/authIndex.js"
let AuthStore = AuthStateStore()

// 获取用户信息
const UserBaseInfo = async () => {
	uni.showLoading({
		title: '加载中',
		mask: true
	})
	if (state.userIMId != 215) {
		let data = await proxy.$get(IMUserInfo + state.userIMId)
		uni.hideLoading();
		if (data.code == 200) {
			state.userInfo = data.data.UserInfo
			state.IsVipImCount = data.data.IsVipImCount
			// 解锁 或者 vip 次数 可以直接聊天
			// 不是会员的时候  
			state.isAuthPup = data.data.IsImUnLock ? false : true
		}
	} else {
		let dataUser = await proxy.$get(UserInfo + state.userIMId)
		uni.hideLoading();
		state.userInfo = dataUser.data
		state.isAuthPup = false
	}

}

let AuthPupRef = ref()
// 金币解锁聊天成功
const TrendUnLockSuccess = () => {
	AuthPupRef.value.squareHideFn()
	UserBaseInfo()
}

onLoad((options) => {
	state.userIMId = Number(options.userIMId)
	// types 1 客服
	state.isAuth = options.types ? false : true
	UserBaseInfo()
	let userInfo = JSON.parse(getAuthorization("userInfo"))
	state.types = userInfo.VipState == 0 && (state.userIMId != 215) ? 1 : 2
	// 男性用户
	if (userInfo.VipState == 1) {
		state.types = 1
	}
	// proxy.nim.getHistoryMsgs({
	// 	scene: 'p2p',
	// 	to: state.userIMId,
	// 	done: getHistoryMsgsDone
	// });
	// function getHistoryMsgsDone(error, obj) {
	// 	console.log('获取p2p历史消息' + (!error ? '成功' : '失败'));
	// 	console.log(error);
	// 	console.log(obj);
	// 	if (!error) {
	// 		console.log(obj.msgs);
	// 	}
	// }
})

const goBack = () => {
	history.back();
}

// 发送图片
const successImg = () => {
	// uni.chooseImage({
	// 	success(paths) {
	// 		// 过滤掉大于50MB的图片
	// 		let filter = paths.tempFiles.filter((item) => {
	// 			return item.size < 52428800;
	// 		});
	// 		uni.showLoading({
	// 			title: '发送图片中',
	// 			mask: true
	// 		});
	// 		for (let item of filter) {
	// 			let reader = new FileReader();
	// 			reader.readAsDataURL(item); // file 转为 base64编码
	// 			reader.onload = function () {
	// 				proxy.nim.sendFile({
	// 					scene: "p2p",
	// 					to: state.userInfo.IMId,
	// 					type: "image",
	// 					dataURL: reader.result, // base64编码
	// 					done: function (error, obj) {
	// 						uni.hideLoading();

	// 						console.log(obj);
	// 						store.addChatMsg({
	// 							chatType: 2,
	// 							isRead: 1,
	// 							msgmsgUserId: getAuthorization('userId'),
	// 							...obj
	// 						});
	// 						// if (error) {
	// 						// 	if (error.message == "sendMsg error: 被拉黑") {
	// 						// 		send_text.value = "";
	// 						// 		getBeBlockedMsg();
	// 						// 	} else {
	// 						// 		toast.value.show({
	// 						// 			title: error.message
	// 						// 		});
	// 						// 	}
	// 						// } else {
	// 						// 	// 将发出的图片 添加入消息列表中
	// 						// 	commit('setChatList', {
	// 						// 		type: 'add',
	// 						// 		listData: [{
	// 						// 			...obj,
	// 						// 			whose: "my",
	// 						// 		}]
	// 						// 	})
	// 						// 	chatContent_ref.value.scrollToEnd();
	// 						// }
	// 					}
	// 				});
	// 			}
	// 		}

	// 	}
	// })

}

const onIsLineFn = (timerNumber) => {
	let num = Date.now() - timerNumber
	let days = num / (60 * 60 * 1000)
	if (days <= 72) {
		return true
	} else {
		return false
	}
}

// 最后在线时间
const onLineFn = (timerNumber) => {
	if (timerNumber) {
		let num = Date.now() - timerNumber
		let days = num / (60 * 60 * 1000)
		if (days <= 24) {
			return Math.ceil(days) + '小时前'
		}
		if (24 < days <= 72) {
			return Math.ceil(days / 24) + '天前'
		}
		if (day > 72) {
			return '离线'
		}
	}
}

let ActionSheetRef = ref()
const squareFn = () => {
	ActionSheetRef.value.actionSheetShow()
}

// 初始化im
import {
	IMUserInfo,
} from "@/api/im/index.js"
import SDK from "@yxim/nim-web-sdk";
import {
	useAccountStore
} from "@/store/index.js"

let store = useAccountStore()

state.chatList = computed(() => {
	let userIMId = state.userIMId == 215 ? 100172 : state.userIMId
	let userId = getAuthorization('userId')
	console.log(userIMId,'userIMId',state.userInfo.IMId,userId)
	store.updateIsRead(userIMId)
	return store.$state.chatListAll.filter(o => ((o.chatType == 1 && o.from == userIMId) || (o.chatType == 2 &&
		o.to == state.userInfo.IMId)) && o.msgUserId == userId)
})

const onMsg = async (msg) => {
	let makeFriendsList = store.$state.makeFriendsList
	let arr = makeFriendsList.map(o => o.IMId)
	msg.chatType = 1
	msg.isRead = 1
	msg.text.replace('送给对方', '对方送你')
	msg.msgUserId = getAuthorization('userId')
	if (!arr.includes(msg.from)) {
		if (state.userIMId != 215) {
			let data = await proxy.$get(IMUserInfo + msg.from)
			data.data.UserInfo.msgUserId = getAuthorization('userId')
			store.addMakeFriends(data.data.UserInfo)
		} else {
			state.userInfo.msgUserId = getAuthorization('userId')
			store.addMakeFriends(state.userInfo)
		}
	}
	store.addChatMsg(msg)
	scollTopStr()
}

let curUserInfo = JSON.parse(getAuthorization("userInfo"))
let IMId = curUserInfo.IMId
let IM_ToKen = curUserInfo.IM_ToKen
state.curUserInfo = curUserInfo
// 不是会员的时候
if (state.curUserInfo.VipState == 0) {
	if (state.curUserInfo.Sex == 0) {
		state.memberType = '1'
	}
	if (state.curUserInfo.Sex == 1) {
		state.memberType = '9'
	}
}

// 成为会员 
// 女性用户
if (state.curUserInfo.VipState > 0 && state.curUserInfo.Sex == 0) {
	state.isAuthPup = false
}
// 男性用户
if (state.curUserInfo.VipState > 0) {
	state.memberType = '9'
}


proxy.nim = SDK.NIM.getInstance({
	debug: false, // 是否开启日志，将其打印到console。集成开发阶段建议打开。
	appKey: "181791f825dd689e4daac44fb7870ce4",
	account: IMId, //用于登录IM
	token: IM_ToKen, //用于登录IM
	db: true, //若不要开启数据库请设置false。SDK 默认为true。
	// privateConf: {}, // 私有化部署方案所需的配置
	// onconnect: onConnect,
	//消息收发的监听事件
	onmsg: onMsg,
});

const sendFn = () => {
	// let store = useAccountStore()
	// store.login(5)
	if (state.msg == '') {
		uni.showToast({
			title: "请输入发送内容",
			icon: "none"
		})
		return
	}
	let {
		IMId
	} = state.userInfo
	proxy.nim.sendText({
		scene: "p2p",
		to: IMId,
		text: state.msg,
		done: sendMsgDone,
	});
};

let scrollRef = ref()

function sendMsgDone(error, msg) {
	let makeFriendsList = store.$state.makeFriendsList
	msg.chatType = 2
	msg.msgUserId = getAuthorization('userId')
	store.addChatMsg(msg)
	state.msg = ""
	scollTopStr()
	let arr = makeFriendsList.map(o => o.IMId)
	let {
		IMId
	} = state.userInfo
	if (!arr.includes(IMId)) {
		state.userInfo.msgUserId = getAuthorization('userId')
		store.addMakeFriends(state.userInfo)
	}
}

const scollTopStr = () => {
	nextTick(() => {
		setTimeout(() => {
			state.scrollTop = scrollRef.value.$el.clientHeight + 600
		}, 500);
	})
}

const successActionGift = (data) => {
	let {
		IMId
	} = state.userInfo
	state.giftShow = false
	let msg = '送给对方' + data.GiftName
	proxy.nim.sendText({
		scene: "p2p",
		to: IMId,
		text: msg,
		done: sendMsgDone,
	});
}



onMounted(() => {
	scollTopStr();
	// setTimeout(() => {
	// 	console.log(
	// 		state.chatList
	// 	);
	// 	proxy.nim.getHistoryMsgs({
	// 		scene: "p2p",
	// 		to: state.userInfo.IMId,
	// 		limit: 50,
	// 		endTime: 0,
	// 		done: (error, {
	// 			msgs
	// 		}) => {
	// 			if (!error) {
	// 				state.chatList = msgs;
	// 			}
	// 		},
	// 	});
	// }, 500)

})
</script>

<style lang="scss" scoped>
.private-chat-head {
	position: fixed;
	width: 100vw;
	box-sizing: border-box;
	z-index: 99;
	top: 0;
	display: flex;
	justify-content: space-between;
	color: #fff;
	align-items: center;
	padding: 30rpx;
	height: 120rpx;
	background-color: #fff;

	.content-swiper-head-left {
		display: flex;
		align-items: center;

		.private-chat-name {
			display: flex;
			align-items: center;
			justify-content: center;

			text {
				color: #333;
				font-size: 32rpx;
			}
		}

		.on-line {
			display: inline-block;
			font-size: 24rpx;
			color: #028f17;
			background: #d3fcd8;
			margin-top: 10rpx;
			height: 24rpx;
			line-height: 24rpx;
			padding: 0 5rpx;
		}
	}



	.content-swiper-head-right {
		display: flex;
		align-items: center;

		:deep(.view-item-image-head-attention-cur) {
			background: #333;
			color: #fff;
		}

		:deep(.view-item-image-head-attention) {
			border-color: #333;
			color: #333;
		}
	}
}

.private-chat-main {
	background: #F7F8F9;
	padding-top: 160rpx;
	min-height: calc(100vh - 180rpx);
}

.private-chat-main-box {
	position: fixed;
	top: 120rpx;
	bottom: 200rpx;
	width: 100%;
	// overflow: auto;
}

.scroll-Y {
	position: fixed;
	height: calc(100% - 336rpx);
	width: 100%;
}

.chat-tips-box {
	display: flex;
	justify-content: center;
	padding-top: 20rpx;

	.chat-tips {
		font-size: 20rpx;
		color: #AEADAD;
		padding: 5rpx 20rpx;
		background: #fff;
		border-radius: 100rpx;
	}
}

.private-chat-input {
	z-index: 99;
	padding: 20rpx;
	background: #fff;
	position: fixed;
	bottom: 0;
	width: 100vw;
	box-sizing: border-box;

	.van-field {
		border-radius: 40rpx;
		background: #F7F8F9;
		border: 1px solid #E5E4E4;
		font-size: 28rpx;
		border: none;

		:deep(.van-field__control) {
			font-size: 28rpx;
		}
	}

}

.private-chat-input-top {
	display: flex;
	align-items: center;

	img {
		flex: none;
		width: 40rpx;
		height: 40rpx;
		margin-left: 20rpx;
	}
}

.img-item {
	width: 40rpx;
	margin-right: 20rpx;
}

.private-chat-input-bottom {
	display: flex;
	align-items: center;
}

:deep(.content-swiper-bottom-message-gift) {
	display: flex;
	align-items: center;
}

.van-button {
	flex: none;
	margin-left: 10rpx;
}

.out-line {
	background: #e2e2e2;
	color: #666;
	padding: 3rpx 5rpx;
	font-size: 20rpx;
}
</style>
